<?php


namespace app\admin\controller;


use api\crm\model\CityModel;
use app\admin\model\CompanyModel;
use app\admin\model\CustomerSourceSettingModel;
use app\admin\model\CustomerStatusModel;
use app\admin\model\UserModel;
use app\admin\model\UserRoleModel;
use app\admin\model\WechatSettingModel;
use cmf\controller\AdminBaseController;
use plugins\wechat\model\TemplateMessageModel;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\Validate;

class CompanyController extends AdminBaseController
{
    public function index()
    {
        $cityFilePath = Env::get('root_path') . 'public/plugins/pca.json';
        //$cityFilePath = Env::get('root_path') . 'public/static/city.json';
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $page = isset($data['page']) && $data['page'] ? intval($data['page']) : 1;
            $num = 10;
            $where = [];
            $list = CompanyModel::where($where)
                ->order('create_time desc')
                ->paginate($num, false, ['page' => $page])->each(function ($item) {
                    if ($item['region']) {
                        $item['region'] = json_decode($item['region']);
                    }
                    return $item;
                });
            $this->success('', '', $list);
        }
        $cityFilePath = Env::get('root_path') . 'public/plugins/pca.json';
        //$cityFilePath = Env::get('root_path') . 'public/static/city.json';
        $cityFile = fopen($cityFilePath, "r");
        $city = json_decode(fread($cityFile, filesize($cityFilePath)));
        $arr = [];
        foreach ($city as $k => $v) {
            $one_arr = [
                'value' => $k,
                'label' => $k,
                'children' => [],
            ];
            foreach ($v as $a => $b) {
                $two_arr = [
                    'value' => $a,
                    'label' => $a,
                    'children' => [],
                ];
                foreach ($b as $c => $d) {
                    $three_arr = [
                        'value' => $d,
                        'label' => $d,
                    ];
                    array_push($two_arr['children'], $three_arr);
                }
                array_push($one_arr['children'], $two_arr);
            }
            array_push($arr, $one_arr);
        }
        //dump($arr);die;
        fclose($cityFile);
        $this->assign('city', json_encode($arr));
        return $this->fetch();
    }

    public function update()
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $data = $this->request->param();
                $validate = new Validate([
                    'name' => 'require|unique:company',
                    'contact_people' => 'require',
                    'contact_mobile' => 'require',
                    'end_time' => 'require',
                ]);
                $validate->message([
                    'name.require' => '请输入公司名称',
                    'name.unique' => '公司名称存在相同',
                    'contact_mobile.require' => '请输入联系号码',
                    'contact_people.require' => '请输入联系人',
                    'end_time.require' => '请输入到期时间',
                ]);
                if (!$validate->check($data)) {
                    throw new Exception($validate->getError());
                }
                $data['region'] = json_encode($data['region']);
                if (isset($data['id']) && $data['id']) {
                    $company_model = CompanyModel::get($data['id']);
                    $company_model->name = $data['name'];
                    $company_model->contact_people = $data['contact_people'];
                    $company_model->contact_mobile = $data['contact_mobile'];
                    $company_model->end_time = $data['end_time'];
                    $company_model->region = $data['region'];
                } else {
                    $company_model = CompanyModel::create($data);

                }
                $res = $company_model->save();
                if ($res) {
                    if (isset($data['id']) && $data['id']) {
                        $company_id = $data['id'];
                    } else {
                        $company_id = $company_model->id;
                        $user_role_model = new UserRoleModel();
                        $id = UserRoleModel::order('id desc')->limit(1)->value('id');
                        $exits_role  = UserRoleModel::where(['name'=>'公司','company_id'=>$company_id])->find();
                        if(empty($exits_role)){
                            $list = [
                                ['name' => '公司', 'parent_id' => 0, 'company_id' => $company_model->id],
                                ['name' => '店长', 'parent_id' => $id + 1, 'company_id' => $company_model->id],
                                ['name' => '业务经理', 'parent_id' => $id + 2, 'company_id' => $company_model->id],
                                ['name' => '审核员', 'parent_id' => $id + 1, 'company_id' => $company_model->id],
                                ['name' => '客户经理', 'parent_id' => $id + 3, 'company_id' => $company_model->id],
                                ['name' => '设计师', 'parent_id' => $id + 5, 'company_id' => $company_model->id],
                            ];
                            $user_role_model->saveAll($list, false);
                        }


                        // 添加分享设置 初识默认值
                        // 推荐用户注册会员卡得积分
                        Db::name('option')->insert([
                            'option_name' => 'user_card_register'.$company_id,
                            'option_value'=> 10,
                            'company_id'  => $company_id
                        ]);

                        // 推荐用户购买产品得积分比例
                        Db::name('option')->insert([
                            'option_name' => 'user_buy'.$company_id,
                            'option_value'=> 0.01,
                            'company_id'  => $company_id
                        ]);

                        // 分享奖励说明 sharing_of_rewards
                        Db::name('option')->insert([
                            'option_name' => 'sharing_of_rewards'.$company_id,
                            'option_value'=> '分享奖励说明',
                            'company_id'  => $company_id
                        ]);


                    }
                    $ssj = CustomerSourceSettingModel::where(['company_id' => $company_id, 'name' => '设计师推荐'])->find();
                    if (empty($ssj)) {
                        $setting_model = CustomerSourceSettingModel::create([
                            'name' => '设计师推荐',
                            'extend_field' => '设计师',
                            'company_id' => $company_id,
                        ]);
                        $setting_model->save();
                    }
                    $status = CustomerStatusModel::where(['company_id' => $company_id, 'name' => '成交'])->find();
                    if (empty($status)) {
                        $customer_status = CustomerStatusModel::create([
                            'name' => '成交',
                            'company_id' => $company_id,
                            'type' => 0
                        ]);
                        $customer_status->save();
                    }
                    $setting = WechatSettingModel::where('company_id', $company_id)->value('setting');
                    if (empty($setting)) {
                        $wechat_setting['server_address'] = 'http://fangtai.0513app.cn/plugin/wechat/wechat/oauth_callback?id=' . $company_id;
                        $wechat_setting['notify_url'] = 'http://fangtai.0513app.cn/plugin/wechat/wechat/notify/id/' . $company_id;
                        $wechat_setting_model = WechatSettingModel::create([
                            'company_id' => $company_id,
                            'setting' => serialize($wechat_setting)
                        ]);
                        $wechat_setting_model->save();
                    }

                    $message_log = TemplateMessageModel::where(['company_id' => $company_id, 'template_title' => '跟进记录驳回通知'])->find();
                    if (empty($message_log)) {
                        $message_log = TemplateMessageModel::create([
                            'company_id' => $company_id,
                            'template_title' => '跟进记录驳回通知',
                            'template_content' => '{{first.DATA}} 日期：{{keyword1.DATA}} 客户姓名：{{keyword2.DATA}} 联系方式：{{keyword3.DATA}} 提交人：{{keyword4.DATA}} 审核员：{{keyword5.DATA}} {{remark.DATA}}',
                            'status' => 0
                        ]);
                        $message_log->save();
                    }
                    $message_log = TemplateMessageModel::where(['company_id' => $company_id, 'template_title' => '审核驳回通知'])->find();
                    if (empty($message_log)) {
                        $message_log = TemplateMessageModel::create([
                            'company_id' => $company_id,
                            'template_title' => '审核驳回通知',
                            'template_content' => '{{first.DATA}} 审核信息：{{keyword1.DATA}} 审核人：{{keyword2.DATA}} 驳回原因：{{keyword3.DATA}} 驳回日期：{{keyword4.DATA}} {{remark.DATA}}',
                            'status' => 0
                        ]);
                        $message_log->save();
                    }
                    $message_log = TemplateMessageModel::where(['company_id' => $company_id, 'template_title' => '客户加入申请审批通知'])->find();
                    if (empty($message_log)) {
                        $message_log = TemplateMessageModel::create([
                            'company_id' => $company_id,
                            'template_title' => '客户加入申请审批通知',
                            'template_content' => '{{first.DATA}} 添加日期：{{keyword1.DATA}} 客户姓名：{{keyword2.DATA}} 手机号码：{{keyword3.DATA}} 客户来源：{{keyword4.DATA}} 客户经理：{{keyword5.DATA}} {{remark.DATA}}',
                            'status' => 0
                        ]);
                        $message_log->save();
                    }
                    $message_log = TemplateMessageModel::where(['company_id' => $company_id, 'template_title' => '跟进记录审核通知'])->find();
                    if (empty($message_log)) {
                        $message_log = TemplateMessageModel::create([
                            'company_id' => $company_id,
                            'template_title' => '跟进记录审核通知',
                            'template_content' => '{{first.DATA}} 客户姓名：{{keyword1.DATA}} 联系方式：{{keyword2.DATA}} 进度标签：{{keyword3.DATA}} 客户状态：{{keyword4.DATA}} 提交人：{{keyword5.DATA}} {{remark.DATA}}',
                            'status' => 0
                        ]);
                        $message_log->save();
                    }
                    $message_log = TemplateMessageModel::where(['company_id' => $company_id, 'template_title' => '客户审核驳回通知'])->find();
                    if (empty($message_log)) {
                        $message_log = TemplateMessageModel::create([
                            'company_id' => $company_id,
                            'template_title' => '客户审核驳回通知',
                            'template_content' => '{{first.DATA}} 客户姓名：{{keyword1.DATA}} 联系方式：{{keyword2.DATA}} 审核员：{{keyword3.DATA}} 驳回原因：{{keyword4.DATA}} {{remark.DATA}}',
                            'status' => 0
                        ]);
                        $message_log->save();
                    }

                    //$wechat_setting[]
                    Db::commit();
                    $this->success('添加成功');
                } else {
                    throw new  Exception('添加失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
    }

    public function delete()
    {
        if ($this->request->isPost()) {
            $model = CompanyModel::withCount(['user_list' => function ($query) {
                $query->where('is_delete', 0);
            }])->get(input('post.id'));
            if ($model) {
                if ($model['user_list_count'] > 0) {
                    $this->error('该公司下还有未删除用户');
                }
                $res = $model->delete();
                if ($res) {
                    $this->success('ok');
                } else {
                    $this->error('fail');
                }
            } else {
                $this->error('数据异常');
            }
        }
    }

    public function get_company_list()
    {
        if ($this->request->isAjax()) {
            $admin_id = cmf_get_current_admin_id();
            $admin_info = UserModel::get($admin_id);
            if ($admin_info['company_id']) {
                $this->success('', '', []);
            } else {
                $list = CompanyModel::all();
                $this->success('', '', $list);
            }

        }
    }
}
